package com.fantasy.blog.service.impl;

import com.alibaba.fastjson.JSON;
import com.fantasy.blog.dao.pojo.SysUser;
import com.fantasy.blog.service.RegisterService;
import com.fantasy.blog.service.SysUserService;
import com.fantasy.blog.utils.JWTUtils;
import com.fantasy.blog.vo.ErrorCode;
import com.fantasy.blog.vo.Result;
import com.fantasy.blog.vo.params.LoginParams;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class RegisterServiceImpl implements RegisterService {

    private static final String slat = "fantasy421!@#";

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public Result register(LoginParams loginParams) {
        String account = loginParams.getAccount();
        String nickname = loginParams.getNickname();
        String password = loginParams.getPassword();
        if(StringUtils.isBlank(account)
                || StringUtils.isBlank(password)
                || StringUtils.isBlank(nickname)
        ){
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        }

        SysUser sysUser = sysUserService.findUserByAccount(account);

        if(null != sysUser){
            return Result.fail(ErrorCode.ACCOUNT_IS_EXIST.getCode(),ErrorCode.ACCOUNT_IS_EXIST.getMsg());
        }
        sysUser = new SysUser();
        sysUser.setAccount(account);
        sysUser.setNickname(nickname);
        sysUser.setPassword(DigestUtils.md5Hex(password+slat));
        sysUser.setCreateDate(System.currentTimeMillis());
        sysUser.setLastLogin(System.currentTimeMillis());
        sysUser.setAvatar("/static/user/user_1.png");
        sysUser.setAdmin(1); //1 为true
        sysUser.setDeleted(0); // 0 为false
        sysUser.setSalt("");
        sysUser.setStatus("");
        sysUser.setEmail("");
        sysUserService.save(sysUser);

        String token = JWTUtils.createToken(sysUser.getId());
        redisTemplate.opsForValue().set("TOKEN_"+token, JSON.toJSONString(sysUser));
        return Result.success(token);
    }
}
